import { phoneNumberReg, specialCharReg } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import * as moment from 'moment';
import { createMemberRecord, queryMemberCardNames } from '../service';
import type { CreateMemberRecordType } from '../types.d';
import { useEffect, useState } from 'react';
import { getMemeberCard } from '../../MemberCard/service';
import { mapOptions } from '../../utils';
import { OptionTypes } from '@/utils/types.d';

export default (props: { reload: () => void }) => {
  const [cardNo, setCardNo] = useState<string>('');
  // const [currCard, setCurrCard] = useState<MemberCardTableItem | null>(null);
  const [currCardMemberTypes, setCurrCardMemberTypes] = useState<OptionTypes[]>([]);

  useEffect(() => {
    if (!cardNo) return;
    getMemeberCard(cardNo).then((res) => {
      if (!res.success) {
        message.error({ key: 'add_record', content: res?.message });
        return;
      }
      // setCurrCard(res.data)
      if (!res.data) return;
      setCurrCardMemberTypes(() => mapOptions(res.data));
    });
  }, [cardNo]);
  return (
    <ModalForm<CreateMemberRecordType>
      title="添加会员卡"
      width="45vw"
      layout="horizontal"
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setCurrCardMemberTypes([]);
        },
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={
        <Button type="primary">
          <PlusOutlined /> 添加
        </Button>
      }
      onFinish={async (values) => {
        const data2create: CreateMemberRecordType = {
          cardNo: values.cardNo,
          plateNumber: values.plateNumber,
          memberName: values.memberName,
          phone: values.phone,
          type: values.type,
        };
        if (values.startTime) {
          data2create.startTime = moment(values.startTime).format('YYYY-MM-DD HH:mm:ss');
        }
        const res = await createMemberRecord(data2create);
        if (res.success) {
          message.success({ key: 'add_record', content: res.message });
          props.reload();
          setCurrCardMemberTypes([]);
          return true;
        }
        message.error({ key: 'add_record', content: res.message });
        return false;
      }}
    >
      {/* <ProFormText name="cardNo" label="模板卡号" placeholder="请填写模板卡号" required /> */}
      <ProFormSelect
        name="cardNo"
        label="模板卡名"
        width="lg"
        debounceTime={300}
        required
        showSearch
        placeholder="请选择模板卡"
        rules={[{ required: true, message: '请选择模板卡' }]}
        fieldProps={{
          onChange: (val) => {
            setCardNo(val);
          },
        }}
        request={(val) => queryMemberCardNames(val?.keyWords)}
      />
      <ProFormSelect
        label="会员类型"
        width="lg"
        required
        name="type"
        fieldProps={{
          notFoundContent: (
            <div
              style={{
                width: '100%',
                minHeight: '100px',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                fontSize: '16px',
              }}
            >
              请确认所选择的模板卡是否支持会员类型选择
            </div>
          ),
        }}
        options={currCardMemberTypes}
      />
      <ProFormText
        name="phone"
        label="手机号码"
        placeholder="请填写手机号码"
        width="lg"
        required
        rules={[
          {
            validator: (_, val) => {
              if (!val || !phoneNumberReg.test(val))
                return Promise.reject(new Error('手机号不符合规范，必须为以1开头的11位数字'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormText
        name="plateNumber"
        label="车牌号码"
        placeholder="请填写车牌号码"
        required
        width="lg"
        rules={[
          {
            validator: (_, val) => {
              if (!val || specialCharReg.test(val))
                return Promise.reject(new Error('车牌号码不符合规范，不支持包含特殊字符'));
              return Promise.resolve(val);
            },
          },
        ]}
      />

      <ProFormText
        name="memberName"
        label="用户昵称"
        width="lg"
        placeholder="请填写用户昵称"
        rules={[
          {
            validator: (_, val) => {
              if (val && specialCharReg.test(val))
                return Promise.reject(new Error('用户昵称不符合规范，不支持包含特殊字符'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormDateTimePicker
        width="lg"
        label="开始时间"
        placeholder="请选择开始时间"
        name="startTime"
      />
    </ModalForm>
  );
};
